/**
 * @description tag菜单标签
 */
import { defineStore } from "pinia";
import { createLocalStorage } from "@/utils/cache";
import { TAB } from "@/enums/cacheEnum";
import { toRaw, unref } from "vue";
import { router } from "@/router/setupRouter";

const t = (val) => val;
let ls = createLocalStorage();

export const useTab = defineStore("app_tab", {
	state: () => {
		return {
			currentTab: {},
			currentIndex: -1,
			tabList: [
				{
					path: "/home",
					name: "首页",
					meta: { icon: null, title: t("routes.menu.home") }
				}
			]
		};
	},
	getters: {
		getCurrentTab() {
			return ls.getItem(TAB.APP_CURRENT_TAB) || this.currentTab;
		},
		getTabList() {
			return ls.getItem(TAB.APP_TAB_LIST) || this.tabList;
		}
	},
	actions: {
		/**
		 * 改变当前 tab
		 */
		changeTab(route) {
			let currentRoute = toRaw(route);
			this.currentTab = currentRoute;
			let result = this.tabList.findIndex(
				(tab) => tab.path == currentRoute.path
			);
			if (result == -1) {
				this.setTab(currentRoute);
			}
		},
		//设置路由
		setTab(route) {
			this.tabList.push(JSON.parse(JSON.stringify(route)));
		},
		//删除某个tag
		deleteTag(path) {
			let result = this.tabList.findIndex((tab) => tab.path == path);
			this.tabList.splice(result, 1);
			if (this.currentTab.path == path) {
				let currentRouteIndex = result > 0 ? result - 1 : 0;
				router.replace({
					path: this.tabList[currentRouteIndex].path
				});
			}
		},
		/**
		 * 批量删除右边
		 * @param {Object} route 选中的路由
		 */
		deleteRightTab(route) {
			let index = this.tabList.findIndex((item) => {
				item.path == route.path;
			});
			//当前在右边
			if (this.currentIndex > index) {
				this.currentIndex = index;
				this.currentTab = route;
			}
			this.tabList = this.tabList.slice(0, index);
			this.save();
		},
		//本地存储
		save() {
			ls.setItem(TAB.APP_TAB_LIST, this.tabList);
			ls.setItem(TAB.APP_CURRENT_TAB, this.currentTab);
			ls.setItem(APP_CURRENT_INDEX, this.currentIndex);
		}
	}
});
